const crypto = require("crypto");
const fs = require("fs");
const path = require("path");

class RSA {
    constructor() {
        this.publicKey = fs.readFileSync(path.resolve( __dirname,'./properties/rsa_public_key.pem'), "utf8");
        this.privateKey = fs.readFileSync(path.resolve( __dirname,'./properties/rsa_private_key.pem'), "utf8");
        this.passphrase = 'mySecret';
    }

    /**
     * 公钥加密
     * @param {string} data 明文字符串
     * @returns {string} 加密后的 Base64 字符串
     */
    publicEncrypt(data) {
        const buffer = Buffer.from(data, "utf8");
        const encrypted = crypto.publicEncrypt(
            {
                key: this.publicKey,
                padding: crypto.constants.RSA_PKCS1_PADDING,
            },
            buffer
        );
        return encrypted.toString("base64");
    }

    /**
     * 私钥解密
     * @param {string} encryptedData 加密的 Base64 字符串
     * @returns {string} 解密后的明文字符串
     */
    privateDecrypt(encryptedData) {
        const buffer = Buffer.from(encryptedData, "base64");
        const decrypted = crypto.privateDecrypt(
            {
                key: this.privateKey,
                passphrase: this.passphrase,
                padding: crypto.constants.RSA_PKCS1_PADDING,
            },
            buffer
        );
        return decrypted.toString("utf8");
    }

    /**
     * 私钥加密
     * @param {string} data 明文字符串
     * @returns {string} 加密后的 Base64 字符串
     */
    privateEncrypt(data) {
        const buffer = Buffer.from(data, "utf8");
        const encrypted = crypto.privateEncrypt(
            {
                key: this.privateKey,
                passphrase: this.passphrase,
                padding: crypto.constants.RSA_PKCS1_PADDING,
            },
            buffer
        );
        return encrypted.toString("base64");
    }

    /**
     * 公钥解密
     * @param {string} encryptedData 加密的 Base64 字符串
     * @returns {string} 解密后的明文字符串
     */
    publicDecrypt(encryptedData) {
        const buffer = Buffer.from(encryptedData, "base64");
        const decrypted = crypto.publicDecrypt(
            {
                key: this.publicKey,
                padding: crypto.constants.RSA_PKCS1_PADDING,
            },
            buffer
        );
        return decrypted.toString("utf8");
    }
}

module.exports = RSA;
